package cn.wolfcode.shop.cloud.web.controller;

import cn.wolfcode.shop.cloud.pay.AlipayConfig;
import cn.wolfcode.shop.cloud.service.ISeckillOrderInfoService;
import com.alipay.api.AlipayApiException;

import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import domain.OrderInfo;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Map;

@RestController
public class PayController {

    @Autowired
    private AlipayClient alipayClient;
    @Autowired
    private AlipayConfig alipayConfig;
    @Autowired
    private ISeckillOrderInfoService seckillOrderInfoService;

    @RequestMapping("/payOrder")
    public void payOrder(String orderNo, HttpServletResponse response) throws Exception {
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(alipayConfig.getReturn_url());//设置同步回调的地址
        alipayRequest.setNotifyUrl(alipayConfig.getNotify_url());//设置异步回调的地址

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = orderNo;
        OrderInfo orderInfo = seckillOrderInfoService.queryByOrderNo(orderNo);
        //付款金额，必填
        String total_amount = orderInfo.getSeckillPrice() + "";
        //订单名称，必填
        String subject = orderInfo.getGoodName();
        //商品描述，可空
        String body = orderInfo.getGoodName();

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");


        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        PrintWriter out = response.getWriter();
        response.setContentType("text/html;charset=utf-8");
        //输出
        out.println(result);
    }


    @RequestMapping("/notify_url")
    public void notify_url(@RequestParam Map<String, String> params, HttpServletResponse response)
            throws IOException, AlipayApiException {
        System.out.println("异步回调时间为" + new Date());
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayConfig.getAlipay_public_key(),
                alipayConfig.getCharset(), alipayConfig.getSign_type()); //调用SDK验证签名
        PrintWriter out = response.getWriter();
        if (signVerified) {//验证成功
            //商品订单号
            String out_trade_no = params.get("out_trade_no");
            //幂等性操作   订单流水表  1.流水插入一条数据   订单编号为主键
          seckillOrderInfoService.changPayStatus(out_trade_no, OrderInfo.STATUS_ACCOUNT_PAID);
            out.print("success");
        } else {//验证失败
            out.print("fail");
        }
    }

    @RequestMapping("/return_url")
    public void return_url(@RequestParam Map params, HttpServletResponse response) throws AlipayApiException, IOException {
        System.out.println("同步回调时间" + new Date());
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayConfig.getAlipay_public_key(),
                alipayConfig.getCharset(), alipayConfig.getSign_type()); //调用SDK验证签名

        //获取订单编号
        String out_trade_no = (String) params.get("out_trade_no");
        if (signVerified) {
            response.sendRedirect("http://localhost/order_detail.html?orderNo=" + out_trade_no);
        } else {
//            out.println("验签失败");
            response.sendRedirect("http://localhost/50x.html");
        }
    }

}
